//
//  NetworkingCenter.m
//  runteraters
//
//  Created by Sebastian Borggrewe on 14/12/2011.
//  Copyright 2011 Robolo. All rights reserved.
//	File created using Singleton XCode Template by Mugunth Kumar (http://blog.mugunthkumar.com)
//  More information about this template on the post http://mk.sg/89	
//  Permission granted to do anything, commercial/non-commercial with this file apart from removing the line/URL above

#import "NetworkingCenter.h"
#import "BaseMessage.h"

@implementation NetworkingCenter


#pragma mark -
#pragma mark Message Handling

- (void) incomingMessage:(NetworkMessage *)msg{
    [[NSNotificationCenter defaultCenter] postNotificationName:NETWORKING_NOTIFICATION object:msg];
}



#pragma mark -
#pragma mark Custom Methods

// Add your custom methods here
- (id) init {
    
    // Init object
    self = [super init];
    
    if (!self) return nil;
    
    // Initialize variables
    isRunning = NO;
    
    return self;
}

/* Open connection to game server on
 * seperate Thread
 */
- (void) openConnectionToServer {
    // If the client thread has not been initialized yet,
    // create it.
    if (clientThread == nil)
        clientThread = [[ClientThreadController alloc] init];
    
    [clientThread setMessageDelegate:self];
    
    [clientThread startNetworkingThreadConnectToAddress:@"127.0.0.1" onPort:SERVER_PORT];
    
    isRunning = YES;
}

/* close connection to game server and clean up
 */
- (void) closeConnectionToServer {
    [clientThread stopNetworkingThread];
    [clientThread setMessageDelegate:nil];
    
}

- (void) sendMessage:(id<NSCoding>)message {
    
    NetworkMessage *msg = [[NetworkMessage alloc] initWithType:[message getMessageType] msgId:123 data:message];
    
    [clientThread sendMessageToServer:msg];
}


#pragma mark -
#pragma mark Singleton Methods

+ (NetworkingCenter*)defaultServer {
    
	static NetworkingCenter *_sharedInstance;
	if(!_sharedInstance) {
		static dispatch_once_t oncePredicate;
		dispatch_once(&oncePredicate, ^{
			_sharedInstance = [[super allocWithZone:nil] init];
        });
    }
    
    return _sharedInstance;
}

+ (id)allocWithZone:(NSZone *)zone {	
    
	return [self defaultServer];
}


- (id)copyWithZone:(NSZone *)zone {
	return self;	
}

#if (!__has_feature(objc_arc))

- (id)retain {	
    
	return self;	
}

- (unsigned)retainCount {
	return UINT_MAX;  //denotes an object that cannot be released
}

- (oneway void) release {
	//do nothing
}

- (id)autorelease {
    
	return self;	
}
#endif

@end
